package com.simtek.simplayer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.WindowManager.LayoutParams;
import android.widget.FrameLayout;

import com.simtek.simplayer.R.dimen;
import com.simtek.simplayer.R.drawable;
import com.simtek.simplayer.R.string;
import com.simtek.simplayer.controller.PlayerController;
import com.simtek.simplayer.utils.SystemUtils;
import com.simtek.simplayer.window.StandOutWindow;
import com.simtek.simplayer.window.constants.StandOutFlags;
import com.simtek.simplayer.window.ui.Window;

public class VideoPlayerWindow extends StandOutWindow {
	public static final short	WINDOW_MODE_MINIMIZE			= 0;
	public static final short	WINDOW_MODE_FULLSCREEN_WIDTH	= 1;
	public static final short	WINDOW_MODE_FULLSCREEN			= 2;

	//
	private static final String	ACTION_UPDATE_WINDOW			= "ACTION_UPDATE_WINDOW";
	private static final String	ACTION_CHANGE_WINDOW_RATIO		= "ACTION_CHANGE_WINDOW_RATIO";
	private static final String	ACTION_CHANGE_MODE				= "ACTION_CHANGE_MODE";

	//
	private static final double	DEFAULT_VIDEO_RATIO				= 16d / 9d;
	private int					miniWindowWidth;
	private double				ratio							= DEFAULT_VIDEO_RATIO;
	private BroadcastReceiver	receiver;
	public static short			currentScreenMode;

	public static int getWindowId() {
		return DEFAULT_ID;
	}

	@Override
	public void onCreate() {
		miniWindowWidth = getResources().getDimensionPixelSize(dimen.minimize_window_width);
		super.onCreate();

		// default
		receiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				if (intent.getAction().equals(
						Intent.ACTION_CONFIGURATION_CHANGED)) {
					if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
						if (currentScreenMode == WINDOW_MODE_FULLSCREEN_WIDTH) {
							showFullScreen(VideoPlayerWindow.this);
						}
					}
				}
			}
		};
		registerReceiver(receiver, new IntentFilter(Intent.ACTION_CONFIGURATION_CHANGED));
	}

	@Override
	public void onDestroy() {
		if (receiver != null) {
			unregisterReceiver(receiver);
			receiver = null;
		}
		super.onDestroy();
	}

	@Override
	public String getAppName() {
		return getString(string.app_name);
	}

	@Override
	public int getAppIcon() {
		return drawable.ic_launcher;
	}

	@Override
	public String getPersistentNotificationTitle(int id) {
		String title = null;
		if (PlayerController.getInstance().playingVideoEntry != null) {
			title = PlayerController.getInstance().playingVideoEntry.getTitle();
		}
		if (title == null) {
			return super.getPersistentNotificationTitle(id);
		}
		return title;
	}

	@Override
	public String getPersistentNotificationMessage(int id) {
		return getString(string.string_click_to_close);
	}

	@Override
	public Intent getPersistentNotificationIntent(int id) {
		return StandOutWindow.getCloseIntent(this, VideoPlayerWindow.class, id);
	}

	@Override
	public void createAndAttachView(int id, FrameLayout frame) {
		PlayerController.getInstance().onCreateView(this, LayoutInflater.from(this), frame);
		frame.addView(PlayerController.getInstance().contentView);
	}

	@Override
	public boolean onShow(int id, Window window) {
		PlayerController.getInstance().onCreate(this);
		receiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				String action = intent.getAction();
				if (Intent.ACTION_CALL.equals(action)) {
					PlayerController instance = PlayerController.getInstance();
					instance.video.pause();
					instance.bindWindow();
				}
			}
		};
		IntentFilter filter = new IntentFilter(Intent.ACTION_CALL);
		// filter.addAction(Intent.action_)
		registerReceiver(receiver, filter);
		return super.onShow(id, window);
	}

	@Override
	public boolean onClose(int id, Window window) {
		FullScreenActionActivity.hide(this);
		PlayerController.onDestroy();
		return super.onClose(id, window);
	}

	// the window will be centered
	@Override
	public StandOutLayoutParams getParams(int id, Window window) {

		currentScreenMode = WINDOW_MODE_FULLSCREEN_WIDTH;

		return buildWindowParams(currentScreenMode,
				new StandOutLayoutParams(id));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		try {
			if (intent != null) {
				String action = intent.getAction();
				Window window = getWindow(getWindowId());
				if (ACTION_UPDATE_WINDOW.equals(action)) {
					updatePersistentNotification(getWindowId());
					return START_NOT_STICKY;
				} else if (ACTION_CHANGE_MODE.equals(action)) {
					if (window != null) {
						short screenMode = intent.getShortExtra("mode", WINDOW_MODE_MINIMIZE);
						StandOutLayoutParams layout = window.getLayoutParams();

						buildWindowParams(screenMode, layout);

						if (screenMode == WINDOW_MODE_FULLSCREEN) {
							FullScreenActionActivity.show(this,
									currentScreenMode);
						} else {
							FullScreenActionActivity.hide(this);
						}

						//
						updateViewLayout(getWindowId(), layout);
						currentScreenMode = screenMode;
						PlayerController.getInstance().onWindowModeChange(
								screenMode);
					}
					return START_NOT_STICKY;
				} else if (ACTION_CHANGE_WINDOW_RATIO.equals(action)) {
					ratio = intent.getDoubleExtra("ratio", DEFAULT_VIDEO_RATIO);
					ratio = Math.max(0, ratio);

					Log.d("video", "window ratio #" + ratio);
					if (window != null) {
						StandOutLayoutParams layout = window.getLayoutParams();
						switch (currentScreenMode) {
							case WINDOW_MODE_MINIMIZE:
								layout.width = miniWindowWidth;
								layout.height = (int) (miniWindowWidth / ratio);
								FullScreenActionActivity.hide(this);
								break;
							case WINDOW_MODE_FULLSCREEN_WIDTH:
								// TODO
								FullScreenActionActivity.hide(this);
								break;
							case WINDOW_MODE_FULLSCREEN:
								layout.width = LayoutParams.MATCH_PARENT;
								layout.height = LayoutParams.MATCH_PARENT;
								break;
						}

						updateViewLayout(getWindowId(), layout);
						PlayerController.getInstance().onWindowRatioChange();
					}
					return START_NOT_STICKY;
				}
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return super.onStartCommand(intent, flags, startId);
	}

	private StandOutLayoutParams buildWindowParams(short screenMode,
			StandOutLayoutParams layout) {
		int[] size = SystemUtils.getDisplaySize(this);

//		int screenWidth = Math.min(size[0], size[1]);

		switch (screenMode) {
			case WINDOW_MODE_FULLSCREEN:
				layout.x = 0;
				layout.y = 0;
				layout.width = LayoutParams.MATCH_PARENT;
				layout.height = LayoutParams.MATCH_PARENT;
				break;
			case WINDOW_MODE_FULLSCREEN_WIDTH:
				layout.x = 0;
				layout.y = 0;
				layout.gravity = Gravity.TOP | Gravity.LEFT;
				layout.width = LayoutParams.MATCH_PARENT;

				layout.height = (int) (Math.min(size[0], size[1]) / ratio);
				break;
			case WINDOW_MODE_MINIMIZE:
				layout.gravity = Gravity.TOP | Gravity.LEFT;
				layout.width = miniWindowWidth;
				layout.height = (int) (miniWindowWidth / ratio);
//			layout.setCenter();

				layout.x = layout.y = Math.max(size[0], size[1]);
				break;
		}
		return layout;
	}

	public static void updateWindow(Context context) {
		context.startService(new Intent(context, VideoPlayerWindow.class)
				.setAction(ACTION_UPDATE_WINDOW).putExtra("id", getWindowId()));
	}

	public static void showFullScreen(Context context) {
		context.startService(new Intent(context, VideoPlayerWindow.class)
				.setAction(ACTION_CHANGE_MODE).putExtra("id", getWindowId())
				.putExtra("mode", WINDOW_MODE_FULLSCREEN));
	}

	public static void showFullWidth(Context context) {
		context.startService(new Intent(context, VideoPlayerWindow.class)
				.setAction(ACTION_CHANGE_MODE).putExtra("id", getWindowId())
				.putExtra("mode", WINDOW_MODE_FULLSCREEN_WIDTH));
	}

	public static void showMinizeWindow(Context context) {
		context.startService(new Intent(context, VideoPlayerWindow.class)
				.setAction(ACTION_CHANGE_MODE).putExtra("id", getWindowId())
				.putExtra("mode", WINDOW_MODE_MINIMIZE));
	}

	public static void changeWindowRatio(Context context, double ratio) {
		context.startService(new Intent(context, VideoPlayerWindow.class)
				.setAction(ACTION_CHANGE_WINDOW_RATIO)
				.putExtra("id", getWindowId()).putExtra("ratio", ratio));
	}

	// move the window by dragging the view
	@Override
	public int getFlags(int id) {
		return super.getFlags(id) | StandOutFlags.FLAG_BODY_MOVE_ENABLE
				| StandOutFlags.FLAG_WINDOW_EDGE_LIMITS_ENABLE
				| StandOutFlags.FLAG_WINDOW_FOCUSABLE_DISABLE;
	}

}
